package net.hn.hnms.biz.upkafka.service;

import io.micrometer.core.instrument.util.IOUtils;
import net.hn.hnms.biz.upkafka.config.KafkaProperties;
import net.hn.hnms.biz.upkafka.config.ServerConfig;
import net.hn.hnms.biz.upkafka.config.SpringContextUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class FTPClientProducer {

    // 存储每种文件类型的最后读取时间
    private Map<String, Date> lastReadTimes = new HashMap<>();


    public List<String> readFtpFiles(String ip,String user,String pass,String directory,String type) {
        //获取当前煤矿编码
        ServerConfig serverConfig = SpringContextUtil.getBean(ServerConfig.class);
        String mineCode = serverConfig.getMineCode();

        initLastReadTimes();
        String ftpServer = ip;  // 替换为实际的 FTP 服务器地址
        int ftpPort = 21;  // 替换为实际的 FTP 端口
        String ftpUsername = user;  // 替换为实际的用户名
        String ftpPassword = pass;  // 替换为实际的密码
        String ftpDirectory = directory;  // 指定要访问的 FTP 文件夹目录

        FTPClient ftpClient = new FTPClient();
        try {

            ftpClient.connect(ftpServer, ftpPort);
            ftpClient.login(ftpUsername, ftpPassword);
            if ("150621011015".equals(mineCode)) {
                //高头窑调整为主动模式
                ftpClient.enterLocalActiveMode();  // 在此处设置主动模式
            }
            // 切换到指定目录
            ftpClient.changeWorkingDirectory(ftpDirectory);

            // 获取文件列表
//            FTPFile[] files = ftpClient.listFiles();
            // 获取.txt 文件列表
            FTPFile[] files = ftpClient.listFiles();
            List<FTPFile> txtFiles = new ArrayList<>();
            if (files!= null) {
                for (FTPFile file : files) {
                    if (!file.isDirectory() && file.getName().endsWith(".txt")) {
                        txtFiles.add(file);
                    }
                }
            }

            if (txtFiles.isEmpty()) {
                // 如果.txt 文件列表为空，返回错误信息或进行相应处理
//                return Collections.singletonList("No.txt files found in the specified directory");
                System.out.println("No.txt files found in the specified directory");
                return new ArrayList<>();
            }

            // 按照文件类型分类
            Map<String, List<FTPFile>> fileMap = new HashMap<>();
            for (FTPFile file : txtFiles) {
                String fileName = file.getName();
                String fileType = fileName.split("_")[1];
                if (!fileMap.containsKey(fileType)) {
                    fileMap.put(fileType, new ArrayList<>());
                }
                fileMap.get(fileType).add(file);
            }

            //获取此类型所有文件
            List<FTPFile> ftpFiles = fileMap.get(type);
            if (ftpFiles ==null ||ftpFiles.isEmpty()) {
//                return Collections.singletonList("No files of type " + type + " found in the specified directory");
                System.out.println(type+"No files of type " + type + " found in the specified directory");
                return new ArrayList<>();
            }
            // 对该类型的文件按照时间排序
//            ftpFiles.sort(Comparator.comparing(f -> {
//                String time = f.getName().split("_")[2].substring(0, 14);
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//                try {
//                    return sdf.parse(time);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    return null;
//                }
//            }));
            //排序且去重
            List<FTPFile> distinctFtpFiles = ftpFiles.stream()
                    .sorted(Comparator.comparing(f -> {
                        String time = f.getName().split("_")[2].substring(0, 14);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        try {
                            return sdf.parse(time);
                        } catch (Exception e) {
                            e.printStackTrace();
                            return null;
                        }
                    }))
                    .distinct()
                    .collect(Collectors.toList());


            List<String> results = new ArrayList<>();
            Date lastReadTime = lastReadTimes.get(type);
            if (lastReadTime == null) {
                //找不到此文件类型的最后读取时间 默认以最新一个文件的时间为准（会获取此类型所有文件）
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTime(new Date());
//                calendar.add(Calendar.YEAR, -1);
//                lastReadTime = calendar.getTime();
                lastReadTime = new Date();
            }

            for (FTPFile file : distinctFtpFiles) {
                String fileName = file.getName();
                String time = fileName.split("_")[2].substring(0, 14);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                Date fileTime = null;
                try {
                    fileTime = sdf.parse(time);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

                if (fileTime.after(lastReadTime)) {
                    // 读取文件内容
                    InputStream inputStream = ftpClient.retrieveFileStream(fileName);
                    if (inputStream == null) {
                        // 文件不存在或无法读取
                        System.out.println("File not found: " + fileName);
                        continue;
                    }
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,StandardCharsets.UTF_8))) {
                        StringBuilder content = new StringBuilder();
                        String line;
                        while ((line = reader.readLine())!= null) {
                            content.append(line);
                            //如果文件存在下一行就追加
                            if (reader.ready()) {
                                content.append("\n");
                            }
                        }
                        results.add(content.toString());
                        // 更新最后读取时间
                        lastReadTimes.put(type, fileTime);
                        // 调用ftpClient.completePendingCommand()解决第二次读取为空情况
                        ftpClient.completePendingCommand();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return results;
        } catch (IOException e) {
            e.printStackTrace();
            return Collections.singletonList("Error occurred while reading from FTP server");
        } finally {
            try {
                updateAndSaveLastReadTimes(type, lastReadTimes.get(type));
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        FTPClientProducer FTPClientProducer = new FTPClientProducer();
        List<String> results = FTPClientProducer.readFtpFiles("192.168.21.162","ftphn","hn@2024","upload","RYXX");
        System.out.println("results = " + results);
    }
    // 从指定的Linux目录读取文件来初始化最后读取时间
    private void initLastReadTimes() {
        File file = null;
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            // windows路径下分隔符替换
            file = new File("C:\\\\kafka\\\\last_read_times.txt");
        } else if (osName.contains("nux") || osName.contains("nix")) {
             file = new File("/home/kafka/last_read_times.txt");
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine())!= null) {
                String[] parts = line.split(":");
                if (parts.length == 2) {
                    String type = parts[0];
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = sdf.parse(parts[1]);
                    lastReadTimes.put(type, date);
                }
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }
    // 更新并保存最后读取时间到文件
    private void updateAndSaveLastReadTimes(String fileType, Date date) {
        lastReadTimes.put(fileType, date);
        File file = null;
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            // windows路径下分隔符替换
            file = new File("C:\\\\kafka\\\\last_read_times.txt");
        } else if (osName.contains("nux") || osName.contains("nix")) {
            file = new File("/home/kafka/last_read_times.txt");
        }
//        File file = new File("/home/kafka/last_read_times.txt");
        try {
            StringBuilder content = new StringBuilder();
            // 先尝试读取原文件内容
            if (file.exists()) {
                try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                    String line;
                    while ((line = reader.readLine())!= null) {
                        String[] parts = line.split(":");
                        if (parts.length == 2 && parts[0].equals(fileType)) {
                            // 如果是要更新的类型，替换时间
                            content.append(fileType).append(":").append(new SimpleDateFormat("yyyyMMddHHmmss").format(date)).append("\n");
                        } else {
                            // 其他行保持不变
                            content.append(line).append("\n");
                        }
                    }
                }
            } else {
                // 如果文件不存在，直接追加新内容
                content.append(fileType).append(":").append(new SimpleDateFormat("yyyyMMddHHmmss").format(date)).append("\n");
            }
            // 写入更新后的内容
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                writer.write(content.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
